﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YServer
{
    /// <summary>
    /// 字节数组流，用于写入各种数据，最后 getbuffer() 得出最终的字节数组
    /// </summary>
    class ByteArray
    {
        MemoryStream ms;
         BinaryReader br;
         BinaryWriter bw;

        public ByteArray() {
            ms = new MemoryStream();
            br = new BinaryReader(ms);
            bw = new BinaryWriter(ms);
        }

        /// <summary>
        /// 有参构造，用于读取时使用
        /// </summary>
        /// <param name="buffer"></param>
        public ByteArray(byte[] buffer) {
            ms = new MemoryStream(buffer);
            br = new BinaryReader(ms);
            bw = new BinaryWriter(ms);
        }

        public int Position { get { return (int)ms.Position; } }

        public void Close() {
            br.Close();
            bw.Close();
            ms.Close();
        }


        public int Length { get { return (int)ms.Length; } }

        public bool Readable { get { return ms.Position < ms.Length; } }

        public void ResetPos() { ms.Position = 0; }

        public void write(int value)
        {
            bw.Write(value);
        }
        public void write(byte value)
        {
            bw.Write(value);
        }
        public void write(bool value)
        {
            bw.Write(value);
        }
        public void write(string value)
        {
            bw.Write(value);
        }
        public void write(byte[] value)
        {
            bw.Write(value);
        }

        public void write(double value)
        {
            bw.Write(value);
        }
        public void write(float value)
        {
            bw.Write(value);
        }
        public void write(long value)
        {
            bw.Write(value);
        }

        public void read(out int value)
        {
            value = br.ReadInt32();
        }
        public void read(out byte value)
        {
            value = br.ReadByte();
        }
        public void read(out bool value)
        {
            value = br.ReadBoolean();
        }
        public void read(out string value)
        {
            value = br.ReadString();
        }
        public void read(out byte[] value, int length)
        {
            value = br.ReadBytes(length);
        }

        public void read(out double value)
        {
            value = br.ReadDouble();
        }
        public void read(out float value)
        {
            value = br.ReadSingle();
        }
        public void read(out long value)
        {
            value = br.ReadInt64();
        }

        public byte[] GetBuffer() {
            byte[] date = new byte[ms.Length];
            Buffer.BlockCopy(ms.GetBuffer(), 0, date, 0, (int)ms.Length);
            return date;
        }

    }
}
